<template>
  <div class="markdown">
    <div class="container">
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
        :inline="true"
        size="small"
      >
        <el-form-item label="博客标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="博客描述" prop="description">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="cateId">
          <el-select v-model="form.cateId" clearable>
            <el-option
              v-for="item in cateOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <mavon-editor
        v-model="content"
        ref="md"
        @imgAdd="$imgAdd"
        @change="change"
        style="min-height: 500px"
      />
      <div class="btns">
        <el-button @click="goBack" size="small">返 回</el-button>
        <el-button @click="handleSave" size="small" type="primary"
          >保 存</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import blogsApi from "@/api/blogs";
export default {
  name: "blogContent",
  components: {
    mavonEditor,
  },
  props: {
    id: {
      type: Number,
    },
    dialog: {
      type: Boolean,
    },
  },
  data() {
    return {
      cateOptions: [],
      form: {
        id: null,
        userId: null,
        title: null,
        description: null,
        cateId: null,
        content: "",
      },
      rules: {
        title: [
          { required: true, message: "博客标题不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "博客描述不能为空", trigger: "blur" },
        ],
        cateId: [
          { required: true, message: "博客分类不能为空", trigger: "change" },
        ],
      },
      content: "",
      html: "",
      configs: {},
      userInfo: {},
    };
  },
  watch: {
    dialog(newValue, oldValue) {
      if (!this.dialog) {
        this.form = {};
        this.form.userId = this.userInfo.id;
        this.html = "";
        this.content = "";
      }else{
        if(this.id){
          this.getBlog();
        }
      }
    },
  },
  created() {
    this.userInfo = this.$store.getters.getUser;
    this.form.userId = this.userInfo.id;
    this.getCateList();
    this.getBlog();
  },
  methods: {
    // 更加id获取博客信息
    getBlog() {
      if (this.id) {
        blogsApi
          .getBlogById(this.id)
          .then(({ data: res }) => {
            if (res.code === 200) {
              res.data.data.cateId = res.data.data.cateId + "";
              this.form = res.data.data;
              this.content = res.data.data.content;
            } else {
              return false;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 将图片上传到服务器，返回地址替换到md中
    $imgAdd(pos, $file) {
      let formdata = new FormData();

      this.$upload
        .post("/上传接口地址", formdata)
        .then((res) => {
          this.$refs.md.$img2Url(pos, res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 所有操作都会被解析重新渲染
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      this.html = render;
      this.form.content = this.content;
    },
    // 获取博客一级分类
    getCateList() {
      blogsApi
        .getCateOne()
        .then(({ data: res }) => {
          if (res.code === 200) {
            res.data.list.forEach((item) => {
              item.id = item.id + "";
            });
            this.cateOptions = res.data.list;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    goBack() {
      this.form = {};
      this.html = "";
      this.content = "";
      this.$emit("close-editor", false);
    },

    handleSave() {
      this.$refs.form.validate((v) => {
        if (v) {
          if (this.form.id) {
            this.handleEdit();
          } else {
            this.handleAdd();
          }
        }
      });
    },
    // 添加博客
    handleAdd() {
      blogsApi
        .add(this.form)
        .then(({ data: res }) => {
          if (res.code === 200) {
            this.$message.success("添加博客成功");
            this.$emit("close-editor", false);
            this.form = {};
            this.form.userId = this.userInfo.id;
            this.html = "";
            this.content = "";
            this.id = null;
          } else {
            this.$message.error("添加博客失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 编辑博客
    handleEdit() {
      blogsApi
        .edit(this.form)
        .then(({ data: res }) => {
          if (res.code === 200) {
            this.$message.success("编辑博客成功");
            this.$emit("close-editor", false);
            this.form = {};
            this.form.userId = this.userInfo.id;
            this.html = "";
            this.content = "";
            this.id = null;
          } else {
            this.$message.error("编辑博客失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.btns {
  width: 100%;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>